package com.gonsin.project.creator;

import com.gonsin.project.creator.list.ListCmd;
import com.gonsin.project.creator.create.CreateCmd;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

public class Main {

    public static void main(String[] args) {
        try {
            System.out.println("欢迎使用GProject项目创建工具");
//            System.out.println("当前默认编码格式：" + Charset.defaultCharset());
//            System.out.println("当前命令行的编码格式：" + Charset.defaultCharset());
            if(args.length == 0 || args.length == 1 || isHelp(args)){
                usages(args[0]);
                return;
            }

            String cmd = args[1];
            if("create".equalsIgnoreCase(cmd)){
                String template = getTemplate(args);
                if(!StringUtils.isEmpty(template)){
                    new CreateCmd(template).run(args);
                }
                return;
            }

            if("list".equalsIgnoreCase(cmd)){
                new ListCmd().run(args);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            usages(args[0]);
        }
    }

    /**
     * 获取命令行中的模板
     * @param args
     * @return
     */
    private static String getTemplate(String[] args) {
        for(int i = 0; i < args.length; i++){
            if("create".equals(args[i])){
                i++;
                if(args.length > i){
                    return args[i];
                }
            }
        }
        return null;
    }


    /**
     * 是否为帮助
     */
    private static boolean isHelp(String[] args) {
        if(args == null || args.length == 0){
            return true;
        }
        String[] help = new String[]{"-h", "--help", "-H", "--h", "--H", "help"};
        for(String a : args){
            if(ArrayUtils.contains(help, a)){
                return true;
            }
        }
        return false;
    }

    private static void usages(String jarPath) {
        try {
            jarPath = jarPath.trim();
            String content = FileUtils.readFileToString(new File(jarPath + ".usage"), "UTF8");
            p(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void p(Object object){
        System.out.println(object);
    }

}
